<?php

/**
 * 用户对象
 * @author Nemo <nemo.xiaolan@gmail.com>
 */

class User extends BaseModel {
    
    public $email;
    
    public $uid;
    
    public $is_admin = false;
    
    public $is_login = false;
    
    public $blogs = array();
    
    public $table = "users";
    
    public function __construct() {
        parent::__construct();
        if($this->is_login()) {
            $this->is_login = true;
            foreach($_SESSION["member"] as $k=>$v) {
                $this->$k = $v;
            }
        }
    }
    
    /**
     * 注册用户名和密码
     */
    public function register($email, $password) {
        
        if($this->get_by($email, "email")) {
            return array("email", "邮箱已经被注册");
        }
        
        $ip = ip2long(get_client_ip());
        $uid = $this->insert(array(
            "email" => $email,
            "password" => $this->generate_password($password),
            "reg_time" => CURRENT_TIMESTAMP,
            "reg_ip"   => $ip,
            "last_login_time" => CURRENT_TIMESTAMP,
            "last_login_ip" => $ip,
            "is_admin" => 0
        ));
        if(!$uid) {
            return false;
        }
        
        $this->login($email, $password);
        return true;
    }
    
    public function login($email, $password) {
        $user = $this->get_by($email, "email");
        if(!$user) {
            return array("email", "这个邮箱还没有注册");
        }
        
        list(, $start, $length) = explode('__', $user['password']);
        
        if($this->generate_password($password, $start, $length) != $user['password']) {
            return array("pwd", "密码不正确");
        }
        
        $this->edit($user["id"], array(
            "last_login_time" => CURRENT_TIMESTAMP,
            "last_login_ip" => ip2long(get_client_ip())
        ));
        
        $blogs = $this->get_list(array("uid" => $user["id"]), "id ASC", "blogs");
        
        $_SESSION["member"] = array(
            "uid" => $user["id"],
            "email" => $user["email"],
            "is_admin" => $user["is_admin"],
            "blogs" => $blogs
        );
        
        return true;
    }
    
    public function logout() {
        unset($_SESSION["member"]);
    }
    
    /**
     * 生成一个密码
     * @param string $password 明文密码
     * @param integer $start 字符串截取开始
     * @param integer $length 截取多少字符串
     * @return string hashed password
     */
    private function generate_password($password, $start = null, $length = null) {
        $length = $length !== null ? $length : rand(18, 25);
        $start = $start !== null ? $start : rand(0, 32-$length);
        $password = substr(md5($password), $start, $length);
        return sprintf("%s__%s__%s", $password, $start, $length);
    }
    
    private function is_login() {
        return isset($_SESSION["member"]);
    }
    
}